

<script lang="ts">
import { Component, Vue, Prop } from "vue-property-decorator";
import { Switch } from "element-ui";
/**
 *
 * element-switch组件增强,支持在状态改变前拦截change事件
 *
 * 用法和element-switch一样
 *
 * {Function} beforChange 同步拦截change事件
 *
 * {Function} beforPromiseChange 异步拦截change事件
 *
 */
@Component({
    // 继承element-switch
    extends: Switch,
    name: "UxSwitch"
})
export default class UxSwitch extends Vue {
    // 同步拦截change事件
    @Prop() beforChange!: Function;
    // 异步拦截change事件
    @Prop() beforPromiseChange!: Function;
    @Prop() data!: any;
    // 重写方法,支持拦截状态改变
    handleChange() {
        const me = this as any,
            val = me.checked ? me.inactiveValue : me.activeValue;
        // 如果有配置beforChange那么return true才不会拦截后续动作
        if (me.beforChange) {
            if (me.beforChange(me.data)) {
                me.checkChange(val);
            }
        } else if (me.beforPromiseChange) {
            // 如果有配置beforPromiseChange那么resolve();才不会拦截后续动作
            me.beforPromiseChange(me.data).then(() => {
                me.checkChange(val);
            });
        } else {
            me.checkChange(val);
        }
    }
    // 拦截拦截状态改变后处理相关逻辑
    checkChange(val: any) {
        const me = this as any;
        // 抛出时间
        me.$emit("input", val);
        me.$emit("change", val);
        me.$nextTick(() => {
            // set input's checked property
            // in case parent refuses to change component's value
            me.$refs.input.checked = me.checked;
        });
    }
}
</script>